package vip.xiaonuo.issued.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vip.xiaonuo.core.pojo.httpclient.ReturnJson;
import vip.xiaonuo.facedoor.modular.device.entity.DeviceCategory;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.memberdevice.constant.MemberDeviceConstant;
import vip.xiaonuo.facedoor.modular.memberdevice.entity.MemberDevice;
import vip.xiaonuo.facedoor.modular.memberdevice.service.MemberDeviceService;
import vip.xiaonuo.facedoor.modular.memberfacestaris.entity.MemberFaceStaris;
import vip.xiaonuo.facedoor.modular.memberfacestaris.service.MemberFaceStarisService;
import vip.xiaonuo.facedoor.modular.memberfeatures.entity.MemberFeatures;
import vip.xiaonuo.facedoor.modular.memberfeatures.service.MemberFeaturesService;
import vip.xiaonuo.facedoor.modular.memberuser.entity.MemberUser;
import vip.xiaonuo.facedoor.modular.memberuser.service.MemberUserService;
import vip.xiaonuo.facedoor.iservice.entity.PersonBaseParam;
import vip.xiaonuo.facedoor.iservice.entity.PersonBaseParamRet;
import vip.xiaonuo.facedoor.iservice.issulog.DeviceLogService;
import vip.xiaonuo.facedoor.remote.iservice.adapter.MemberReqAdapter;
import vip.xiaonuo.facedoor.rule.RuleConstant;
import vip.xiaonuo.facedoor.vo.dewo.GetPersonResponse;
import vip.xiaonuo.facedoor.iservice.IMemberDealWithService;

import javax.annotation.Resource;
import java.util.Objects;

@Service(RuleConstant.DW+ RuleConstant.MEMBER_DEAL_WITH)
public class HttpMemberDealWithServiceImpl implements IMemberDealWithService {
  @Autowired
  private MemberReqAdapter memberReqAdapter;

  @Autowired
  private MemberDeviceService memberDeviceService;

  @Autowired
  private DeviceLogService deviceLogService;

  @Autowired
  private MemberUserService memberUserService;

  @Resource
  private MemberFeaturesService memberFeaturesService;

  @Resource
  private MemberFaceStarisService memberFaceStarisService;


  @Override
  public PersonBaseParamRet getBaseParam(PersonBaseParam personBasePerson) {
    return new PersonBaseParamRet().setUrl("http://" + personBasePerson.getDeviceBase().getCabinetIp() + ":" + personBasePerson.getDeviceBase().getCabinetPort());
  }

  @Override
  public void deleteException(MemberDevice memberDevice, MemberUser memberUser, DeviceBase deviceBase, Exception e) {
    memberDevice.setFailReason(ExceptionUtils.getMessage(e));
    memberDevice.setStatus(MemberDeviceConstant.DELETE_FAIL);
    memberDeviceService.updateById(memberDevice);
    deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), ExceptionUtils.getMessage(e), FAIL, DELETE);
  }

  @Override
  public void delete(MemberDevice memberDevice, MemberUser memberUser, PersonBaseParamRet personBaseParamRet, DeviceBase deviceBase) throws Exception {
    ReturnJson returnJson = memberReqAdapter.deletePerson(memberDevice, personBaseParamRet.getUrl());
    // 删除用户成功
    if (StringUtils.isNotBlank(returnJson.getCode()) && ("0000".equals(returnJson.getCode()) || "0201".equals(returnJson.getCode()))) {
      memberDeviceService.removeById(memberDevice.getId());
      long count = memberDeviceService.count(new LambdaQueryWrapper<MemberDevice>().eq(MemberDevice::getMemberId, memberUser.getId()));
      if (count == 0 && Objects.equals(memberUser.getDelFlag(), "1")) {
        memberUserService.removeById(memberDevice.getMemberId());
        memberFaceStarisService.remove(new LambdaQueryWrapper<MemberFaceStaris>().eq(MemberFaceStaris::getMemberId,memberUser.getId()));
      }
      deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), JSON.toJSONString(returnJson), SUCCESS, DELETE);
      // 删除用户失败
    } else {
      memberDevice.setFailReason(JSON.toJSONString(returnJson));
      memberDevice.setStatus(MemberDeviceConstant.DELETE_FAIL);
      memberDeviceService.updateById(memberDevice);
      deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), JSON.toJSONString(returnJson), FAIL, DELETE);
    }
  }


  @Override
  public void add(MemberDevice memberDevice, MemberUser memberUser, PersonBaseParamRet personBaseParamRet, DeviceBase deviceBase) throws Exception {
    // 先查询人员
    GetPersonResponse getPersonResponse = memberReqAdapter.getPerson(personBaseParamRet.getUrl(), memberUser);
    // 设置特征值
    addMemberFeatures(memberUser, deviceBase);
    // 设置人员楼层信息
    setMemberFloors(memberDevice, memberUser);


    // 存储柜管理员
    if (memberDevice.getLockerAdmin()) {
      memberUser.setPersonType(3);
      memberUser.setLockerData(null);
      memberDevice.setLockerData(null);
    }else if (StringUtils.isNotBlank(memberDevice.getLockerData())) {
        memberUser.setLockerData(memberDevice.getLockerData());
    }

    // 不存在 新增
    if (StringUtils.isNotBlank(getPersonResponse.getCode()) && "0202".equals(getPersonResponse.getCode())) {
      ReturnJson returnJson = memberReqAdapter.addPerson(personBaseParamRet.getUrl(), memberUser);
      if (returnJson.getCode().equals("0000")) {
        deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), JSON.toJSONString(returnJson), SUCCESS, ADD);
        memberDevice.setStatus(MemberDeviceConstant.SYNC_SUCCESS);
        memberDeviceService.updateById(memberDevice);

      } else {
        memberDevice.setFailReason("新增人员发生错误：" + JSON.toJSONString(returnJson));
        memberDevice.setStatus(MemberDeviceConstant.ADD_FAIL);
        memberDeviceService.updateById(memberDevice);
        deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), JSON.toJSONString(returnJson), FAIL, ADD);
      }
      // 修改
    } else if (StringUtils.isNotBlank(getPersonResponse.getCode()) && "0000".equals(getPersonResponse.getCode())) {

      ReturnJson returnJson = memberReqAdapter.updatePerson(personBaseParamRet.getUrl(), memberUser);
      if (returnJson.getCode().equals("0000")) {
        memberDevice.setStatus(MemberDeviceConstant.SYNC_SUCCESS);
        memberDeviceService.updateById(memberDevice);
        deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), JSON.toJSONString(returnJson), SUCCESS, UPDATE);
      } else {
        memberDevice.setFailReason("修改人员发生错误：" + JSON.toJSONString(returnJson));
        memberDevice.setStatus(MemberDeviceConstant.UPDATE_FAIL);
        memberDeviceService.updateById(memberDevice);
        deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), JSON.toJSONString(returnJson), FAIL, UPDATE);
      }
    } else {
      memberDevice.setFailReason("查询人员发生错误：" + JSON.toJSONString(getPersonResponse));
      memberDevice.setStatus(MemberDeviceConstant.ADD_FAIL);
      memberDeviceService.updateById(memberDevice);
      deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), JSON.toJSONString(getPersonResponse), FAIL, ADD);
    }
  }

  private void setMemberFloors(MemberDevice memberDevice, MemberUser memberUser) {
    MemberFaceStaris memberFaceStaris = memberFaceStarisService.getOne(new LambdaQueryWrapper<MemberFaceStaris>()
            .eq(MemberFaceStaris::getMemberId, memberUser.getId())
            .eq(MemberFaceStaris::getDeviceId, memberDevice.getDeviceId()));
    if (memberFaceStaris!=null){
      memberUser.setFloors(memberFaceStaris.getFloors());
    }
  }

  private void addMemberFeatures(MemberUser memberUser, DeviceBase deviceBase) {
    MemberFeatures memberFeatures = null;
    if (ObjectUtil.equal(deviceBase.getDeviceType(), "1")) {
      memberFeatures = memberFeaturesService.getOne(new LambdaQueryWrapper<MemberFeatures>().eq(MemberFeatures::getType, DeviceCategory.SUB_TYPE_FACE).eq(MemberFeatures::getDwMemberUserId, memberUser.getId()));
    } else if (ObjectUtil.equal(deviceBase.getDeviceType(), "5")) {
      memberFeatures = memberFeaturesService.getOne(new LambdaQueryWrapper<MemberFeatures>().eq(MemberFeatures::getType, DeviceCategory.SUB_TYPE_STORE).eq(MemberFeatures::getDwMemberUserId, memberUser.getId()));
    }
    if (memberFeatures != null) {
      memberUser.setProperValue(memberFeatures.getValue());
    } else {
      memberUser.setProperValue(null);
    }
  }


  @Override
  public void addException(MemberDevice memberDevice, MemberUser memberUser, DeviceBase deviceBase, Exception e) {
    // 直接修改为失败
    memberDevice.setFailReason(JSON.toJSONString(ExceptionUtils.getMessage(e)));
    memberDevice.setStatus(MemberDeviceConstant.ADD_FAIL);
    memberDeviceService.updateById(memberDevice);
    deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), ExceptionUtils.getMessage(e), FAIL, ADD);
  }

  @Override
  public void updateException(MemberDevice memberDevice, MemberUser memberUser, DeviceBase deviceBase, Exception e) {
    // 直接修改为失败
    memberDevice.setFailReason(JSON.toJSONString(ExceptionUtils.getMessage(e)));
    memberDevice.setStatus(MemberDeviceConstant.UPDATE_FAIL);
    memberDeviceService.updateById(memberDevice);
    deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), ExceptionUtils.getMessage(e), FAIL, UPDATE);
  }

  @Override
  public void update(MemberDevice memberDevice, MemberUser memberUser, PersonBaseParamRet baseParam, DeviceBase deviceBase) throws Exception {
    // 设置人员楼层信息
    setMemberFloors(memberDevice,memberUser);

    memberUser.setMemberType(1);
      // 存储柜管理员
      if (memberDevice.getLockerAdmin()) {
          memberUser.setPersonType(3);
          memberUser.setLockerData(null);
          memberDevice.setLockerData(null);
      }else if (StringUtils.isNotBlank(memberDevice.getLockerData())) {
          memberUser.setLockerData(memberDevice.getLockerData());
      }

    ReturnJson returnJson = memberReqAdapter.updatePerson(baseParam.getUrl(), memberUser);
    if (StringUtils.isNotBlank(returnJson.getCode()) && ("0000".equals(returnJson.getCode()) || "0201".equals(returnJson.getCode()))) {
      deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), JSON.toJSONString(returnJson), SUCCESS, UPDATE);
      memberDevice.setStatus(MemberDeviceConstant.SYNC_SUCCESS);
      memberDeviceService.updateById(memberDevice);

    } else if (returnJson.getCode().equals("0202")) {
      ReturnJson addRj = memberReqAdapter.addPerson(baseParam.getUrl(), memberUser);
      // 调用新增接口
      if (addRj.getCode().equals("0000")) {
        memberDevice.setStatus(MemberDeviceConstant.SYNC_SUCCESS);
        memberDeviceService.updateById(memberDevice);
        deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), JSON.toJSONString(returnJson), SUCCESS, ADD);
      } else {
        deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), JSON.toJSONString(returnJson), FAIL, ADD);
        memberDevice.setFailReason(JSON.toJSONString(returnJson));
        memberDevice.setStatus(MemberDeviceConstant.ADD_FAIL);
        memberDeviceService.updateById(memberDevice);
      }
    } else {
      memberDevice.setFailReason(JSON.toJSONString(returnJson));
      memberDevice.setStatus(MemberDeviceConstant.UPDATE_FAIL);
      memberDeviceService.updateById(memberDevice);
      deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), JSON.toJSONString(returnJson), FAIL, UPDATE);
    }
  }
}
